﻿using Crossroad.Utils.Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Crossroad.Core.Exceptions;
using Crossroad.Utils.Models;
using Microsoft.AspNetCore.Http;
using Crossroad.Utils;
using System.Threading.Tasks;

namespace Crossroad.Core
{
    public class HttpUtil
    {
        #region 图片上传

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="rootPath">上传根目录</param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static async Task<FileDom> UploadImage(string rootPath, HttpContext content)
        {
            var datafile = content.Request.Form.Files[0];
            // 如果没有上传文件
            if (datafile.FileName.IsNullOrEmpty() || datafile.Length == 0)
                return null;

            var model = new FileDom()
            {
                rootPath = rootPath,
                id = KeyUtil.SerialNo,
                dir = "images",
                name = Path.GetFileName(datafile.FileName)
            };

            //获取文件名称
            var index = model.name.LastIndexOf('.');
            //获取文件后缀名
            model.suffix = model.name.Substring(index, model.name.Length - index);
            // 文件系统不能使用虚拟路径
            if (model.rootPath.IsNullOrEmpty())
                model.rootPath = Directory.GetCurrentDirectory();
            var folder = $@"{model.rootPath}upload\{model.dir}\";
            //如果上传的文件目录不存在
            if (!Directory.Exists(folder))
                //创建文件目录
                Directory.CreateDirectory(folder);

            model.relativePath = $"upload/{model.dir}/{model.id}{model.suffix}";
            model.fullPath = $"{model.rootPath}{model.relativePath.Replace("/", @"\")}";
            using (var stream = new FileStream(model.fullPath, FileMode.Create))
            {
                await datafile.CopyToAsync(stream);
            }

            return model;
        }

        /// <summary>
        /// 图片保存
        /// </summary>
        /// <param name="rootPath">保存根目录</param>
        /// <param name="imageBase64"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static FileDom SaveImage(string rootPath, string imageBase64, string fileName = null)
        {
            if (imageBase64.IsNullOrEmpty())
                throw new LogicException("SaveIamgeErr:图片不能为空");
            byte[] bytes = Convert.FromBase64String(imageBase64);
            var model = new FileDom()
            {
                rootPath = rootPath,
                id = KeyUtil.SerialNo,
                dir = "images",
            };
            model.name = fileName.IsNullOrEmpty() ? $"{model.id}.jpg" : fileName;

            //获取文件名称
            var index = model.name.LastIndexOf('.');
            //获取文件后缀名
            model.suffix = model.name.Substring(index, model.name.Length - index);
            // 文件系统不能使用虚拟路径
            if (model.rootPath.IsNullOrEmpty())
                model.rootPath = Directory.GetCurrentDirectory();
            var folder = $@"{model.rootPath}upload\{model.dir}\";
            //如果上传的文件目录不存在
            if (!Directory.Exists(folder))
                //创建文件目录
                Directory.CreateDirectory(folder);

            model.relativePath = $"upload/{model.dir}/{model.id}{model.suffix}";
            model.fullPath = $"{model.rootPath}{model.relativePath.Replace("/", @"\")}";
            File.WriteAllBytes(model.fullPath, bytes);

            return model;
        }

        #endregion

        #region 附件上传

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="rootPath">上传根目录</param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static async Task<FileDom> UploadFile(string rootPath, HttpContext content)
        {
            var dataFiles = content.Request.Form.Files;
            // 如果没有上传文件
            if (dataFiles.IsNull() || dataFiles.Count == 0)
                return null;
            var fileData = dataFiles[0];

            var model = new FileDom()
            {
                rootPath = rootPath,
                id = KeyUtil.SerialNo,
                dir = "attachment",
                name = Path.GetFileName(fileData.FileName)
            };
            //获取文件名称
            var index = model.name.LastIndexOf('.');
            //获取文件后缀名
            model.suffix = model.name.Substring(index, model.name.Length - index);
            // 文件系统不能使用虚拟路径
            if (model.rootPath.IsNullOrEmpty())
                model.rootPath = Directory.GetCurrentDirectory();
            var folder = $@"{model.rootPath}upload\{model.dir}\";
            //如果上传的文件目录不存在
            if (!Directory.Exists(folder))
                //创建文件目录
                Directory.CreateDirectory(folder);

            model.relativePath = $"upload/{model.dir}/{model.id}{model.suffix}";
            model.fullPath = $"{model.rootPath}{model.relativePath.Replace("/", @"\")}";
            using (var stream = new FileStream(model.fullPath, FileMode.Create))
            {
                await fileData.CopyToAsync(stream);
            }

            return model;
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="rootPath">上传根目录</param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static async Task<List<FileDom>> UploadFiles(string rootPath, HttpContext content)
        {
            var dataFiles = content.Request.Form.Files;
            // 如果没有上传文件
            if (dataFiles.IsNull() || dataFiles.Count == 0)
                return null;

            //上传文件保存后的文件列表
            var files = new List<FileDom>();
            //循环上传的文件列表
            foreach (var fileData in dataFiles)
            {
                var model = new FileDom()
                {
                    rootPath = rootPath,
                    id = KeyUtil.SerialNo,
                    dir = "attachment",
                    name = Path.GetFileName(fileData.FileName)
                };
                //获取文件名称
                var index = model.name.LastIndexOf('.');
                //获取文件后缀名
                model.suffix = model.name.Substring(index, model.name.Length - index);
                // 文件系统不能使用虚拟路径
                if (model.rootPath.IsNullOrEmpty())
                    model.rootPath = Directory.GetCurrentDirectory();
                var folder = $@"{model.rootPath}upload\{model.dir}\";
                //如果上传的文件目录不存在
                if (!Directory.Exists(folder))
                    //创建文件目录
                    Directory.CreateDirectory(folder);

                model.relativePath = $"upload/{model.dir}/{model.id}{model.suffix}";
                model.fullPath = $"{model.rootPath}{model.relativePath.Replace("/", @"\")}";
                using (var stream = new FileStream(model.fullPath, FileMode.Create))
                {
                    await fileData.CopyToAsync(stream);
                }
                files.Add(model);
            }

            return files;
        }

        #endregion
    }
}
